﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace TransEchoViewer
{
    public class UdpSensor : ITransPort
    {
        public UdpClient udp;
        private int LocalPort = 51888;
        public IPEndPoint Remote = new IPEndPoint(IPAddress.Any, 0);

        // 只是实现接口，与串口统一
        public string PortName { get => "localhost"; set { } }
        public int BaudRate { get => 0; set { } }

        public UdpSensor() { 
        }

        public int BytesToRead => udp is null ? 0 : udp.Available;

        public void DiscardInBuffer()
        {
            int len = udp.Available;
            if (len == 0) return;
            var dum = new byte[len];
            udp.Client.Receive(dum);
        }

        public void Open()
        {
            udp = new UdpClient(new IPEndPoint(IPAddress.Any, LocalPort));
            udp.Client.ReceiveTimeout = 1000;
        }

        public void Read(byte[] buf, int v, int length)
        {
            udp.Client.Receive(buf, 0, length, SocketFlags.None);
        }

        public void Close()
        {
            udp.Close();
        }
    }
}
